<script setup lang="ts">

import { onMounted, reactive, ref } from 'vue'
import { Message, type TableDraggable } from '@arco-design/web-vue'
import type { GeneratorColumns, GeneratorTable } from '@/api/system/generator/generator'
import { tableAdd, tableById, tableModify } from '@/api/system/generator/table'
import { useRoute } from 'vue-router'
import { useGlobalStore } from '@/stores/global'

const activeKey = ref(1)

const query = useRoute().query

//加载数据
onMounted(() => {
  if (query.id) {
    //@ts-ignore
    tableById(Number(query.id)).then((resp: Result<GeneratorTable>) => {
      form.tableForm = resp.data
      form.tableForm.columns.forEach((value, index) => {
        value['index'] = index
      })
      form.columnsIndex = form.tableForm.columns.length + 1
    })
  }
})


//使用系统缓存
const cache = useGlobalStore().cache


const form = reactive({
  selectKeys: [],
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true
  },
  tableForm: {
    tableName: null,
    structName: null,
    commentName: null,
    columns: [{
      weight: 0,
      columnName: 'Id',
      sqlType: 'int',
      condition: '',
      title: 'ID',
      search: false,
      structType: '*int',
      edit: false,
      show: true,
      required: false,
      exportImport: false
    }, {
      weight: 1,
      columnName: 'CreateTime',
      sqlType: 'timestamp',
      condition: '',
      title: '创建时间',
      search: false,
      structType: '*time.Time',
      edit: false,
      show: true,
      required: false,
      exportImport: false
    }, {
      weight: 2,
      columnName: 'UpdateTime',
      sqlType: 'datetime',
      condition: '',
      title: '更新时间',
      search: false,
      structType: '*time.Time',
      edit: false,
      required: false,
      exportImport: false,
      show: false
    }, {
      weight: 3,
      columnName: 'CreateBy',
      sqlType: 'int',
      condition: '',
      title: '创建人',
      search: false,
      structType: '*int',
      edit: false,
      required: false,
      exportImport: false,
      show: false
    }, {
      weight: 4,
      columnName: 'DelBy',
      sqlType: 'int',
      condition: '',
      title: '删除人',
      search: false,
      structType: '*int',
      edit: false,
      required: false,
      exportImport: false,
      show: false
    }, {
      weight: 5,
      columnName: 'Del',
      sqlType: 'int',
      condition: '',
      title: '是否删除',
      search: false,
      structType: '*int',
      edit: false,
      required: false,
      exportImport: false,
      show: false
    }, {
      weight: 6,
      columnName: 'Remark',
      sqlType: 'varchar(20)',
      condition: '',
      title: '备注',
      search: false,
      structType: '*string',
      edit: false,
      required: false,
      exportImport: false,
      show: false
    }
    ] as GeneratorColumns[]
  } as GeneratorTable,
  tableFromRules: {
    tableName: [{ required: true, message: '表名称不能为空' }],
    structName: [{ required: true, message: '结构体名称不能为空' }],
    commentName: [{ required: true, message: '表备注不能为空' }]
  },
  tableFormHandle: ({ values, errors }: any) => {
    console.log(values, errors)
    if (!errors) {
      activeKey.value++
    }
  },
  columnsIndex: 7,
  columnsFormHandle: ({ values, errors }: any) => {
    console.log(JSON.stringify(values), errors)
    if (errors) {
      return
    }

    if (values.length == 0) {
      Message.error('表字段列表为空！！！')
      return
    }

    //如果存在ID，则是修改数据
    if (query.id) {
      tableModify(form.tableForm).then(() => {
        activeKey.value++
      })
      return
    }
    //@ts-ignore
    tableAdd(form.tableForm).then(() => {
      activeKey.value++
    })
  },
  removeCheck: () => {
    const map = new Map()
    form.selectKeys.forEach(val => {
      map.set(val, val)
    })
    form.tableForm.columns = form.tableForm.columns.filter(value => !map.has(value.weight))
    console.log(form.selectKeys)
    form.selectKeys = []
  }
})

const dataType = reactive({
  activeLang: 'Golang',
  language: [
    { label: 'Java', value: 'Java' },
    { label: 'Golang', value: 'Golang' }
  ],
  java: [
    { label: 'Integer', value: 'Integer' },
    { label: 'Float', value: 'Float' },
    { label: 'Double', value: 'Double' },
    { label: 'Boolean', value: 'Boolean' },
    { label: 'Date', value: 'Date' },
    { label: 'Float', value: 'Float' },
    { label: 'Character', value: 'Character' },
    { label: 'String', value: 'String' }
  ],
  go: [
    { label: '*int', value: '*int' },
    { label: '*bool', value: '*bool' },
    { label: '*float', value: '*float' },
    { label: '*rune', value: '*rune' },
    { label: '*string', value: '*string' },
    { label: '*time.Time', value: '*time.Time' },
    { label: '*LocalTime（自行封装）', value: '*LocalTime' }
  ]
})

const pushItem = () => {
  form.tableForm.columns.push({
    generatorTableId: null,
    columnName: null,
    sqlType: null,
    structType: null,
    title: null,
    search: false,
    edit: false,
    show: false,
    required: false,
    condition: null,
    exportImport: false,
    weight: form.columnsIndex++
  } as GeneratorColumns)
}

const draggableChange = (newData: any) => {
  //拖拽之后完成排序
  form.tableForm.columns = newData.map((value: GeneratorColumns, index: number) => {
    value.weight = index
    return value
  })
}

</script>

<template>
  <a-breadcrumb class="my-3">
    <a-breadcrumb-item>系统工具</a-breadcrumb-item>
    <a-breadcrumb-item @click="$router.push('/generator')">代码生成</a-breadcrumb-item>
    <a-breadcrumb-item>表单构建</a-breadcrumb-item>
  </a-breadcrumb>
  <a-layout-content>
    <a-card>
      <template #title>
        <template v-if="!query.id">
          数据库表单构建
        </template>
        <template v-else>
          数据库表单修改
        </template>
      </template>

      <a-row justify="center" class="p-4 mt-4">
        <a-col :span="12">
          <a-steps :current="activeKey">
            <a-step>填写数据表信息</a-step>
            <a-step>填写表字段信息</a-step>
            <a-step>
              <template #icon>
                <IconCheck />
              </template>
              完成
            </a-step>
          </a-steps>
        </a-col>
      </a-row>

      <div>
        <div v-if="activeKey == 1">
          <a-row justify="center">
            <a-col :span="8">
              <a-form ref="tableFormRef" @submit="form.tableFormHandle" :model="form.tableForm"
                      :rules="form.tableFromRules" label-align="left" class="mt-5">
                <a-form-item field="tableName" label="数据表名称" validate-trigger="blur" hide-asterisk>
                  <a-input v-model="form.tableForm.tableName" />
                </a-form-item>
                <a-form-item field="structName" validate-trigger="blur" hide-asterisk>
                  <template #label>
                    结构体名称
                    <a-tooltip content="Golang 结构体必须首字母必须大写" position="bottom">
                      <IconQuestionCircle />
                    </a-tooltip>
                  </template>
                  <a-input v-model="form.tableForm.structName" />
                </a-form-item>
                <a-form-item field="commentName" label="数据表备注" validate-trigger="blur" hide-asterisk>
                  <a-input v-model="form.tableForm.commentName" />
                </a-form-item>
                <a-form-item>
                  <a-row :gutter="15" class="w-100">
                    <a-col :span="8">
                      <a-checkbox v-model="form.tableForm.batchInsert">批量导入导出</a-checkbox>
                    </a-col>
                    <a-col :span="6">
                      <a-checkbox v-model="form.tableForm.batchDelete">批量删除</a-checkbox>
                    </a-col>
                    <a-col :span="7">
                      <a-checkbox v-model="form.tableForm.operationByMe">自有数据
                        <a-tooltip>
                          <IconQuestionCircle />
                          <template #content>
                            登录用户只能操作自己的数据，需要字段名有一个CreateBy
                          </template>
                        </a-tooltip>
                      </a-checkbox>
                    </a-col>
                  </a-row>
                </a-form-item>
                <a-form-item>
                  <a-space>
                    <RouterLink to="/generator">
                      <a-button type="secondary">返回</a-button>
                    </RouterLink>
                    <a-button type="primary" html-type="submit">下一步</a-button>
                  </a-space>
                </a-form-item>
              </a-form>
            </a-col>
          </a-row>
        </div>
        <div v-if="activeKey == 2">
          <a-row justify="center">
            <a-col :span="22">

              <a-space class="mb-3">
                <a-button @click="pushItem" type="primary">
                  <template #icon>
                    <IconPlus />
                  </template>
                  添加
                </a-button>
                <a-button type="secondary" @click="form.removeCheck">
                  <template #icon>
                    <IconDelete />
                  </template>
                  删除
                </a-button>
                <a-select style="width: 180px" v-model="dataType.activeLang">
                  <a-option :label="v.label" :value="v.value" v-for="(v,i) in dataType.language" :key="i" />
                </a-select>
              </a-space>
              <a-form :model="form.tableForm.columns" size="large" ref="columnsFormRef"
                      @submit="form.columnsFormHandle">
                <a-table row-key="weight" v-model:selected-keys="form.selectKeys" :data="form.tableForm.columns"
                         :row-selection="form.rowSelection"
                         :pagination="false" :draggable="{}" @change="draggableChange">
                  <template #columns>
                    <a-table-column data-index="columnName" fixed="left" width="200"
                    >
                      <template #title>
                        字段名
                        <a-tooltip content="Golang 中字段名首字母必须大写" position="bottom">
                          <IconQuestionCircle />
                        </a-tooltip>
                      </template>
                      <template #cell="{rowIndex}">
                        <a-form-item :field="`${rowIndex}.columnName`"
                                     :rules="[{required: true,message:'字段名不能为空'}]"
                                     validate-trigger="blur"
                                     hide-asterisk
                                     hide-label
                        >
                          <a-input v-model="form.tableForm.columns[rowIndex].columnName" />
                        </a-form-item>
                      </template>
                    </a-table-column>


                    <a-table-column title="数据库类型" data-index="sqlType" width="100"
                    >
                      <template #cell="{rowIndex}">
                        <a-form-item :field="`${rowIndex}.sqlType`"
                                     :rules="[{required: true,message:'数据库类型不能为空'}]"
                                     validate-trigger="blur"
                                     hide-asterisk
                                     hide-label

                        >
                          <a-select allow-search allow-create allow-clear v-model=" form.tableForm.columns[rowIndex].sqlType
                        ">
                            <a-option label="tinyint" value="tinyint" />
                            <a-option label="int" value="int" />
                            <a-option label="bigint" value="bigint" />
                            <a-option label="float" value="float" />
                            <a-option label="double（可选精度）" value="double" />
                            <a-option label="decimal" value="decimal" />
                            <a-option label="time" value="time" />
                            <a-option label="date" value="date" />
                            <a-option label="year" value="year" />
                            <a-option label="datetime" value="datetime" />
                            <a-option label="timestamp" value="timestamp" />
                            <a-option label="char" value="char" />
                            <a-option label="varchar（需要指定长度）" value="varchar" disabled />
                            <a-option label="tinyblob" value="tinyblob" />
                            <a-option label="tinytext" value="tinytext" />
                            <a-option label="blob" value="blob" />
                            <a-option label="text" value="text" />
                            <a-option label="mediumblob" value="mediumblob" />
                            <a-option label="mediumtext" value="mediumtext" />
                            <a-option label="longblob" value="longblob" />
                            <a-option label="longtext" value="longtext" />
                          </a-select>
                        </a-form-item>
                      </template>
                    </a-table-column>

                    <a-table-column data-index="title" title="字段名称" width="160">
                      <template #cell="{rowIndex}">
                        <a-form-item
                          :field="`${rowIndex}.title`"
                          :rules="[{required:true,message:'字段名称不能为空'}]"
                          validate-trigger="blur"
                          hide-asterisk
                          hide-label
                        >
                          <a-input v-model="form.tableForm.columns[rowIndex].title" />
                        </a-form-item>
                      </template>
                    </a-table-column>
                    <a-table-column data-index="structType" width="150">
                      <template #title>
                        数据类型
                        <a-tooltip content="语言中对应的数据类型" position="bottom">
                          <IconQuestionCircle />
                        </a-tooltip>
                      </template>
                      <template #cell="{rowIndex}">
                        <a-form-item :field="`${rowIndex}.structType`"
                                     :rules="[{required: true,message:'数据类型不能为空'}]"
                                     validate-trigger="blur"
                                     hide-asterisk
                                     hide-label
                        >
                          <a-select allow-create allow-search allow-clear
                                    v-model="form.tableForm.columns[rowIndex].structType">
                            <template v-if="dataType.activeLang == 'Java'">
                              <a-option :label="v.label" :value="v.value" v-for="(v,i) in dataType.java"
                                        :key="i" />
                            </template>
                            <template v-else>
                              <a-option :label="v.label" :value="v.value" v-for="(v,i) in dataType.go"
                                        :key="i" />
                            </template>
                          </a-select>
                        </a-form-item>
                      </template>
                    </a-table-column>

                    <a-table-column title="搜索" data-index="edit"
                                    align="center"
                                    width="60"
                    >
                      <template #cell="{rowIndex}">
                        <a-form-item :field="`${rowIndex}.search`"
                                     hide-label
                        >
                          <div class="text-center w-100">
                            <a-checkbox v-model="form.tableForm.columns[rowIndex].search"></a-checkbox>
                          </div>
                        </a-form-item>
                      </template>
                    </a-table-column>


                    <a-table-column title="必填" width="60" data-index="required"
                                    align="center"
                    >
                      <template #cell="{rowIndex}">
                        <a-form-item :field="`${rowIndex}.required`"
                                     hide-label
                        >
                          <div class="text-center w-100">
                            <a-checkbox v-model="form.tableForm.columns[rowIndex].required"></a-checkbox>
                          </div>
                        </a-form-item>
                      </template>
                    </a-table-column>
                    <a-table-column title="编辑" width="60" data-index="edit"
                                    align="center"
                    >
                      <template #cell="{rowIndex}">
                        <a-form-item :field="`${rowIndex}.edit`"
                                     hide-label
                        >
                          <div class="text-center w-100">
                            <a-checkbox v-model="form.tableForm.columns[rowIndex].edit"></a-checkbox>
                          </div>
                        </a-form-item>
                      </template>
                    </a-table-column>
                    <a-table-column title="导入导出" width="120" data-index="exportImport"
                                    align="center"
                    >
                      <template #cell="{rowIndex}">
                        <a-form-item :field="`${rowIndex}.exportImport`"
                                     hide-label
                        >
                          <div class="text-center w-100">
                            <a-checkbox v-model="form.tableForm.columns[rowIndex].exportImport"></a-checkbox>
                          </div>
                        </a-form-item>
                      </template>
                    </a-table-column>
                    <a-table-column title="显示" width="60" data-index="show"
                                    align="center"
                    >
                      <template #cell="{rowIndex}">
                        <a-form-item :field="`${rowIndex}.show`"
                                     hide-label
                        >
                          <div class="text-center w-100">
                            <a-checkbox v-model="form.tableForm.columns[rowIndex].show"></a-checkbox>
                          </div>
                        </a-form-item>
                      </template>
                    </a-table-column>


                    <a-table-column title="搜索条件" data-index="condition" width="60">
                      <template #cell="{rowIndex}">
                        <a-form-item :field="`${rowIndex}.condition`"
                                     :rules="[{validator:()=>{ if(form.tableForm.columns[rowIndex].condition) form.tableForm.columns[rowIndex].search},message:'搜索条件不能为空'}]"
                                     validate-trigger="blur"
                                     hide-asterisk
                                     hide-label

                        >
                          <a-select allow-search allow-create v-model=" form.tableForm.columns[rowIndex].condition
                        ">
                            <a-option label="大于" value=">" />
                            <a-option label="小于" value="<" />
                            <a-option label="大于等于" value=">=" />
                            <a-option label="小于等于" value="<=" />
                            <a-option label="模糊" value="like" />
                            <a-option label="等等与" value="=" />
                            <a-option label="不等与" value="!=" />
                          </a-select>
                        </a-form-item>
                      </template>
                    </a-table-column>
                    <a-table-column title="组件" width="200">
                      <template #cell="{rowIndex}">
                        <a-form-item hide-label hide-asterisk>
                          <a-select v-model="form.tableForm.columns[rowIndex].editComponent" allow-clear>
                            <a-option :label="val['key']" :value="val.value"
                                      v-for="(val,index) in cache.sysCache.generatorComponent" :key="index" />
                          </a-select>
                        </a-form-item>
                      </template>
                    </a-table-column>
                    <a-table-column title="数据源" width="150">
                      <template #cell="{rowIndex}">
                        <a-form-item hide-label hide-asterisk>
                          <a-select v-model="form.tableForm.columns[rowIndex].dataSource" allow-clear>
                            <a-option :label="val['key']" :value="val.value"
                                      v-for="(val,index) in cache.sysCache.generatorDatasource" :key="index" />
                          </a-select>
                        </a-form-item>
                      </template>
                    </a-table-column>
                    <a-table-column title="数据列表" width="200">
                      <template #cell="{rowIndex}">
                        <a-form-item hide-label hide-asterisk>
                          <a-select v-model="form.tableForm.columns[rowIndex].dataSourceKey" allow-clear>
                            <a-option :label="val['key']" :value="val.value"
                                      v-for="(val,index) in cache.sysDatabaseCache[form.tableForm.columns[rowIndex].dataSource]"
                                      :key="index" />
                          </a-select>
                        </a-form-item>
                      </template>
                    </a-table-column>
                  </template>
                </a-table>

                <div class="m-4 d-flex justify-content-center">
                  <a-space>
                    <RouterLink to="/generator">
                      <a-button>返回</a-button>
                    </RouterLink>
                    <a-button @click="activeKey--">上一步</a-button>
                    <a-button type="primary" html-type="submit">
                      <template #icon>
                        <IconCheck />
                      </template>
                      提交
                    </a-button>
                  </a-space>
                </div>
              </a-form>
            </a-col>
          </a-row>

        </div>
        <div v-if="activeKey == 3" class="d-flex flex-column align-items-center">
          <div>
            <a-result status="success">
              <template #subtitle>
                提交成功
              </template>
            </a-result>
          </div>
          <div>
            <RouterLink to="/generator">
              <a-button type="primary">返回</a-button>
            </RouterLink>
          </div>
        </div>
      </div>
    </a-card>
  </a-layout-content>
</template>

<style scoped lang="scss">
.arco-tabs-nav::before {
  border: none !important;
}
</style>
